/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.xiongda.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.xiongda.entity.XUser;
import com.jeeplus.modules.xiongda.service.XUserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.xiongda.entity.XCategory;
import com.jeeplus.modules.xiongda.service.XCategoryService;

/**
 * 分类Controller
 * @author 缪琼
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/xiongda/xCategory")
public class XCategoryController extends BaseController {

	@Autowired
	private XCategoryService xCategoryService;
	@Autowired
	private XUserService xUserService;
	
	@ModelAttribute
	public XCategory get(@RequestParam(required=false) String id) {
		XCategory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = xCategoryService.get(id);
		}
		if (entity == null){
			entity = new XCategory();
		}
		return entity;
	}
	
	/**
	 * 分类列表页面
	 */
	@RequiresPermissions("xiongda:xCategory:list")
	@RequestMapping(value = {"list", ""})
	public String list(XCategory xCategory, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<XCategory> page = xCategoryService.findPage(new Page<XCategory>(request, response), xCategory);
		List<XCategory> list = page.getList();
		for (XCategory xCategory1 : list) {
			xCategory1.setXUser(xUserService.get(xCategory1.getXUser().getId()));
			if (xCategory1.getParentIds() != null && xCategory1.getParentIds() != "") {
				String[] strings = xCategory1.getParentIds().split(",");
				int len = strings.length;
				for (int i = 0; i < len; i++) {
					XCategory xCategory2 = xCategoryService.get(strings[i]);
					xCategory1.setParentName(i == 0 ? xCategory2.getName() : xCategory1.getParentName() + " >> " + xCategory2.getName());
				}
			}
		}
		model.addAttribute("page", page);
		return "modules/xiongda/xCategoryList";
	}

	/**
	 * 查看，增加，编辑分类表单页面
	 */
	@RequiresPermissions(value={"xiongda:xCategory:view","xiongda:xCategory:add","xiongda:xCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(XCategory xCategory, Model model) {
		xCategory.setXUser(xUserService.get(xCategory.getXUser().getId()));
		if (xCategory.getParentIds() != null && xCategory.getParentIds() != "") {
			String[] strings = xCategory.getParentIds().split(",");
			int len = strings.length;
			for (int i = 0; i < len; i++) {
				XCategory xCategory1 = xCategoryService.get(strings[i]);
				xCategory.setParentName(i == 0 ? xCategory1.getName() : xCategory.getParentName() + " >> " + xCategory1.getName());
			}
		}
		model.addAttribute("xCategory", xCategory);
		return "modules/xiongda/xCategoryForm";
	}

	/**
	 * 保存分类
	 */
	@RequiresPermissions(value={"xiongda:xCategory:add","xiongda:xCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(XCategory xCategory, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, xCategory)){
			return form(xCategory, model);
		}
		if(!xCategory.getIsNewRecord()){//编辑表单保存
			XCategory t = xCategoryService.get(xCategory.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(xCategory, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			xCategoryService.save(t);//保存
		}else{//新增表单保存
			xCategoryService.save(xCategory);//保存
		}
		addMessage(redirectAttributes, "保存分类成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
	}
	
	/**
	 * 删除分类
	 */
	@RequiresPermissions("xiongda:xCategory:del")
	@RequestMapping(value = "delete")
	public String delete(XCategory xCategory, RedirectAttributes redirectAttributes) {
		xCategoryService.delete(xCategory);
		addMessage(redirectAttributes, "删除分类成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
	}
	
	/**
	 * 批量删除分类
	 */
	@RequiresPermissions("xiongda:xCategory:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			xCategoryService.delete(xCategoryService.get(id));
		}
		addMessage(redirectAttributes, "删除分类成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("xiongda:xCategory:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(XCategory xCategory, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "分类"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<XCategory> page = xCategoryService.findPage(new Page<XCategory>(request, response, -1), xCategory);
    		new ExportExcel("分类", XCategory.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出分类记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("xiongda:xCategory:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<XCategory> list = ei.getDataList(XCategory.class);
			for (XCategory xCategory : list){
				try{
					xCategoryService.save(xCategory);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条分类记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条分类记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入分类失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
    }
	
	/**
	 * 下载导入分类数据模板
	 */
	@RequiresPermissions("xiongda:xCategory:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "分类数据导入模板.xlsx";
    		List<XCategory> list = Lists.newArrayList(); 
    		new ExportExcel("分类数据", XCategory.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xCategory/?repage";
    }
	
	
	

}